package com.sgj.controller;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.AlipayApiException;
import com.sgj.enums.PayTypeEnum;
import com.sgj.handler.AbstractHandler;
import com.sgj.handler.Factory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 请求支付并生成二维码接口
 * @Author: Guoji Shen
 * @Date: 2021/12/1 9:29
 */
@RestController
@RequestMapping("/pay")
public class PayController {

    @PostMapping("/wx/native")
    public void wx(HttpServletResponse response) throws IOException, AlipayApiException {
        // TODO 需要在商户自己的订单表内生成订单，再发出支付请求
        // 生成唯一订单号，暂时用时间戳+随机生成六位数
        StringBuilder sb = new StringBuilder();
        sb.append("WX").append(getNow()).append(RandomUtil.randomInt(100000, 999999));
        // 注意，此处微信的单位为分，乘以100才是最终价格
        AbstractHandler strategy = Factory.getInvokeStrategy(PayTypeEnum.WX_NATIVE);
        strategy.pay("你把钱给我付了", sb.toString(), BigDecimal.valueOf(50000), response);
    }

    @PostMapping("/ali/native")
    public void ali(HttpServletResponse response) throws AlipayApiException, IOException {
        // TODO 需要在商户自己的订单表内生成订单，再发出支付请求
        // 生成唯一订单号，暂时用时间戳+随机生成六位数
        StringBuilder sb = new StringBuilder();
        sb.append("ALI").append(getNow()).append(RandomUtil.randomInt(100000, 999999));
        // 单位为元
        AbstractHandler strategy = Factory.getInvokeStrategy(PayTypeEnum.ALI_NATIVE);
        strategy.pay("你把钱给我付了", sb.toString(), BigDecimal.valueOf(500D), response);
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public Integer getNow() {
        return Integer.valueOf(String.valueOf(new Date().getTime()).substring(0, 10));
    }
}